const Topic = require('../models/topics')
const User = require('../models/users')
class TopicCtl {
    // 查询话题
    async find(ctx) {
        const { per_page = 2 } = ctx.query
        const page = Math.max(ctx.query.page * 1, 1) - 1 // 第几页
        const perPage = Math.max(per_page * 1, 1) // 每页有几条
        // skip 跳过前面的n条数据
        ctx.body = await Topic
            .find({ name: new RegExp(ctx.query.q) })
            .limit(perPage)
            .skip(page * perPage)
    }
    // 查询特定话题
    async findById(ctx) {
        const { fields = '' } = ctx.query
        const selectFields = fields.split(';').filter(f => f).map(f => '+' + f).join(' ')
        const topic = await Topic.findById(ctx.params.id).select(selectFields)
        ctx.body = topic
    }
    // 新建话题
    async create(ctx) {
        ctx.verifyParams({
            name: { type: 'string', required: true },
            avatar_url: { type: 'string', required: false },
            introduction: { type: 'string', required: false },
        })
        const topic = await new Topic(ctx.request.body).save()
        ctx.body = topic
    }
    // 修改话题
    async update(ctx) {
        ctx.verifyParams({
            name: { type: 'string', required: false },
            avatar_url: { type: 'string', required: false },
            introduction: { type: 'string', required: false },
        })
        const topic = await Topic.findByIdAndUpdate(ctx.params.id, ctx.request.body)
        // topic返回的是更新前的
        ctx.body = topic
    }
    async checkTopicExist(ctx, next) {
        const topic = await Topic.findById(ctx.params.id)
        if (!topic) { ctx.throw(404, '话题不存在') }
        await next()
    }
    // 获取某个话题的粉丝
    async listTopicFollwers(ctx) {
        const users = await User.find({ followingTopics: ctx.params.id })
        ctx.body = users
    }
}

module.exports = new TopicCtl()
